/*
 * 代号：凤凰
 * http://www.jphenix.org
 * 2014-06-10
 * V4.0
 */
package com.jphenix.clazz;

import com.jphenix.standard.docs.ClassInfo;

import java.io.DataInputStream;
import java.io.IOException;

/**
 * <code>Exceptions_attribute</code>.
 * @author mabg
 */
@ClassInfo({"2014-06-10 19:55","Exceptions_attribute"})
public class ExceptionsAttribute extends AttributeInfo {
    
    /**
     * The name of this attribute <code>"Exceptions"</code>.
     */
    public static final String tag = "Exceptions";

    ExceptionsAttribute(ConstPool cp, int n, DataInputStream in)
        throws IOException
    {
        super(cp, n, in);
    }


    /**
     * Constructs a new exceptions attribute.
     *
     * @param cp                constant pool table.
     */
    public ExceptionsAttribute(ConstPool cp) {
        super(cp, tag);
        byte[] data = new byte[2];
        data[0] = data[1] = 0;  // empty
        this.info = data;
    }



    /**
     * Returns <code>exception_index_table[]</code>.
     */
    public int[] getExceptionIndexes() {
        byte[] blist = info;
        int n = blist.length;
        if (n <= 2) {
            return null;
        }

        int[] elist = new int[n / 2 - 1];
        int k = 0;
        for (int j = 2; j < n; j += 2) {
            elist[k++] = ((blist[j] & 0xff) << 8) | (blist[j + 1] & 0xff);
        }
        return elist;
    }

    /**
     * Returns the names of exceptions that the method may throw.
     */
    public String[] getExceptions() {
        byte[] blist = info;
        int n = blist.length;
        if (n <= 2) {
            return null;
        }

        String[] elist = new String[n / 2 - 1];
        int k = 0;
        for (int j = 2; j < n; j += 2) {
            int index = ((blist[j] & 0xff) << 8) | (blist[j + 1] & 0xff);
            elist[k++] = constPool.getClassInfo(index);
        }
        return elist;
    }


    /**
     * Returns <code>number_of_exceptions</code>.
     */
    public int tableLength() { return info.length / 2 - 1; }

    /**
     * Returns the value of <code>exception_index_table[nth]</code>.
     */
    public int getException(int nth) {
        int index = nth * 2 + 2;        // nth >= 0
        return ((info[index] & 0xff) << 8) | (info[index + 1] & 0xff);
    }
}
